package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 模拟自定义编写SpringMvc框架
 * 所有的Controller必须继承这个Controller
 * 用户浏览器请求地址: http://localhost:8080/goods?method=goodsList
 * @author 千锋健哥
 */
public class BaseController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //访问地址例如 : http://localhost:8080/goods?method=goodsList
        //1. 通过用户的访问路径, 获取需要访问的方法名称
        String methodName = req.getParameter("method");
        try {
            //2反射获取类对象
            Class clazz = this.getClass();
            //3. 通过反射获取方法对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

            //4. 反射获取这个方法的返回值, 也就是请求转发或者重定向跳转的页面的路径.
            //return "forward:/addGoods.jsp" 或者 "redirect:/addGoods.jsp"
            String jumpUrl = (String)method.invoke(this, req, resp);
            //5. 判断跳转的路径不为空
            if (jumpUrl != null && !"".equals(jumpUrl)) {
                //对方法的返回值字符串按照冒号切割
                String[] urlArray = jumpUrl.split(":");
                if ("forward".equals(urlArray[0])) {
                    //请求转发业务处理
                    //urlArray[1]里面的数据例如: /addGoods.jsp
                    req.getRequestDispatcher(urlArray[1]).forward(req, resp);
                } else if("redirect".equals(urlArray[0])) {
                    //重定向
                    //urlArray[1]里面的数据例如: /addGoods.jsp
                    resp.sendRedirect(urlArray[1]);
                } else {
                    //如果不是请求转发, 也不是重定向规定写法, 那么默认做请求转发
                    req.getRequestDispatcher(jumpUrl).forward(req, resp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
